package org.fire.mina;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import android.util.Log;

public class MinaMessageEncoder extends ProtocolEncoderAdapter {
	private static final String TAG = "MinaMessageEncoder";
	private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		String str = "^" + message.toString() + "$";
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, "JSON: " + str);
		}
		
		IoBuffer buf = IoBuffer.allocate(str.length()).setAutoExpand(true);
		buf.putString(str, encoder);
		buf.flip();
		out.write(buf);
	}

}
